#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include "Util.hpp"
bool CutString(const std::string& in , const std::string& sep , std::string& str1 , std::string& str2)
{
    auto pos = in.find(sep);
    if(pos == std::string::npos) return false;
    str1 = in.substr(0,pos);
    str2 = in.substr(pos+sep.size());
    return true;
}
bool GetQueryString(std::string& query_string)
{
    //1、获取方法
    std::string method;
    char* temp = getenv("METHOD");
    if(temp == nullptr)
    {
        ELOG("None Env:METHOD");
        return false;
    }
    method = temp;
    //判断方法
    if(method == "GET")
    {
        //获取参数
        temp = getenv("ARGS");
        if(temp == nullptr)
        {
            ELOG("None Env:ARGS");
            return false;
        }
        query_string = temp;
    }else if(method == "POST")
    {
        //获取有效载荷长度
        int Content_Length;
        temp = getenv("CONTENT_LENGTH");
        if(temp == nullptr)
        {
            ELOG("None Env:CONTENT_LENGTH");
            return false;
        }
        Content_Length = std::atoi(temp);
        while(Content_Length)
        {
            char ch;
            int n = read(0,&ch,1);
            if(n == 1)
            {
                Content_Length--;
                query_string += ch;
            }
        }
    }
    return true;
}
int main()
{
    std::string query_string;
    bool ret = GetQueryString(query_string);
    //差错处理
    std::string str1 , str2;
    std::string name1 , value1;
    std::string name2 , value2;
    CutString(query_string,"&",str1,str2);
    CutString(str1,"=",name1,value1);
    CutString(str2,"=",name2,value2);
    std::cerr << "##" << name1 << ": " <<value1 << std::endl;
    std::cerr << "##" << name2 << ": " <<value2 << std::endl;
    std::cout << name1 <<" : "<< value1;
    std::cout << name2 <<" : " <<value2;
    return 0;
}